﻿namespace Hippo.Console
{
    using System;
    using System.Configuration;
    using System.ServiceModel;
    using Common;
    using System.Linq;
    using Hippo.Console.Lib;
    using Hippo.Console.Lib.Services;

    public class Program
    {
        public static void Main(string[] args)
        {
            Console.Out.WriteLine("Hippo.Console version " + HippoAssembly.Version);
            Console.Out.WriteLine(HippoAssembly.AssemblyCopyright);
            Console.Out.WriteLine("All Rights Reserved.\n");

            var configuration = new ConsoleConfigurationProfile(ConfigurationManager.AppSettings);
            var parser = new ConsoleCommandLineParser(configuration, new RegexFactory());
            
            parser.Parse(args);
            var scriptFiles = parser.UnrecognizedArguments.ToArray();

            var runSpecification = new RunSpecificationBuilder(new FileSystemWrapper())
                .Build(scriptFiles);

            using (var servicePanel = new ControlServicePanel(new ServiceHost(new ControlService())))
            {
                servicePanel.Open();
                var isConnected = servicePanel.WaitForAgents(configuration.WaitForAgents, configuration.WaitTimeout);

                if (isConnected)
                {
                    servicePanel.Do(callback => callback.StartTest(runSpecification));
                }
                else
                {
                    Console.Error.WriteLine("Agents did not connect in a timely fashion.");
                }

                Console.WriteLine("Press [RETURN] to exit");
                Console.ReadLine();
            }
        }
    }
}
